<template>
  <!-- 页面整体容器 -->
  <view class="content">
    <!-- 头部商家信息 -->
    <view class="shop-header">
      <!-- 商家 logo 图片 -->
      <image class="shop-logo" :src="Config.API_HOST + shop[0].imgUrl" mode="aspectFill"></image>
      <!-- 商家信息区域 -->
      <view class="shop-info">
        <!-- 商家名称 -->
        <text class="shop-name">{{ shop[0].name }}</text>
        <view class="stats-container">
          <text class="stat-item">月售{{ shop[0].sales }}</text>
          <text class="stat-item">起送¥{{ shop[0].expressLimit }}</text>
          <text class="stat-item">运费¥{{ shop[0].expressPrice }}</text>
        </view>
        <text class="slogan">{{ shop[0].slogan }}</text>
      </view>
      <image 
      :src="isFollowed? Config.API_HOST + '/imgs/关注-已关注.png' : Config.API_HOST + '/imgs/关注-未关注.png'" 
      alt="" 
      style="width: 40px;height:40px" 
      @click="select(shop[0]._id)">
    </image>
    </view>

    <!-- 主体内容 -->
    <view class="main-container">
      <!-- 左侧导航栏 -->
      <scroll-view class="nav-sidebar" scroll-y>
        <!-- 循环渲染导航项 -->
        <view
          v-for="(nav, index) in navList"
          :key="index"
          class="nav-item"
          :class="{ active: activeTab === nav.key }"
          @click="switchTab(nav.key)"
        >
          <!-- 导航项标题 -->
          {{ nav.title }}
        </view>
      </scroll-view>

      <!-- 右侧商品列表 -->
      <scroll-view class="product-list" scroll-y>
        <!-- 循环渲染商品卡片 -->
        <view
          v-for="(item, index) in all"
          :key="index"
          class="product-card"
        >
          <!-- 商品图片 -->
          <image class="product-img" :src="Config.API_HOST + item.imgUrl" mode="aspectFill"></image>
          <!-- 商品信息区域 -->
          <view class="product-info">
            <!-- 商品标题 -->
            <text class="product-title">{{ item.name }}</text>
            <!-- 商品已售数量 -->
            <text class="sales">已售{{ item.sales }}</text>
            <!-- 价格容器 -->
            <view class="price-container">
              <!-- 当前价格 -->
              <text class="current-price">¥{{ item.price }}</text>
              <!-- 原价 -->
              <text class="old-price">¥{{ item.oldPrice }}</text>
            </view>
            <!-- 加入购物车按钮，点击触发 addToCart 方法 -->
            <button @click="addToCart(item)" class="add">加入购物车</button>
          </view>
        </view>
      </scroll-view>
    </view>
    <!-- 浮框 -->
    <view class="cart-popup" v-show="showCartPopup">
      <!-- 操作按钮区域 -->
      <view class="cart-ops">
        <view class="clear-cart" @click="confirmClearCart">清空购物车</view>
      </view>
      <!-- 购物车商品列表 -->
      <view class="cart-items">
        <view
          v-for="(cartItem, index) in cartItems"
          :key="index"
          class="cart-item"
        >
          <image class="cart-item-img" :src="Config.API_HOST + cartItem.imgUrl" mode="aspectFill"></image>
          <view class="cart-item-info">
            <text class="cart-item-title">{{ cartItem.name }}</text>
            <text class="cart-item-sales">月售{{ cartItem.sales }}</text>
            <view class="count-value">数量：{{ cartItem.quantity }}</view>
          </view>
          <view class="cart-item-price">
            <text class="cart-current-price">¥{{ cartItem.price }}</text>
          </view>
        </view>
      </view>
    </view>
    <!-- 底部 -->
    <view class="footer-content">
      <view class="cart-total">
        <image :src="Config.API_HOST + '/imgs/basket.png'" mode="" class="shopimg" @click="shows"></image>
		<text class="num">{{num}}</text>
        <text class="total-price">总计：¥{{ totalPrice.toFixed(2) }}元</text>
      </view>
      <button @click="goToCheckout(shop[0].name)" class="checkout-button">去结算</button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import Config from '@/config.js';

// 响应式数据：商家信息，初始化为空数组
const shop = ref([{}]);
// 响应式数据：所有商品信息，初始化为空数组
const all = ref([]);
// 响应式数据：当前激活的导航标签，初始为 'all'
const activeTab = ref('all');
const cartItems = ref([]); // 购物车商品列表
const showCartPopup = ref(false); // 是否显示购物车浮层
const totalPrice = computed(() => {
    return cartItems.value.reduce((acc, item) => acc + (parseFloat(item.price) * parseFloat(item.quantity)), 0);
});
// 新增：购物车商品数量
const num = ref(0); 

// 导航列表数据
const navList = ref([
  { key: 'all', title: '全部商品' },
  { key: 'seckill', title: '限时秒杀' },
  { key: 'fruit', title: '新鲜水果' }
]);
const isFollowed = ref(false);

// 页面加载时触发的生命周期钩子
onLoad((options) => {
  const id = options.id;
  uni.request({
    url: Config.API_HOST + `/hotList?_id=${id}`,
    success: (res) => {
      shop.value = res.data;
      loadProducts('all');
      // 在获取商家信息后立即获取购物车数据
      fetchCartData();
    }
  });
});

// 切换导航标签的方法
const switchTab = (type) => {
  activeTab.value = type;
  loadProducts(type);
};

// 加载商品数据的方法
const loadProducts = (type) => {
  const apiMap = {
    all: `/products-all?shopId=${shop.value[0]._id}`,
    seckill: `/kill?shopId=${shop.value[0]._id}`,
    fruit: `/fruit?shopId=${shop.value[0]._id}`
  };
  uni.request({
    url: Config.API_HOST + apiMap[type],
    success: (res) => all.value = res.data
  });
};

// 加入购物车的方法
const addToCart = (item) => {
  const token = uni.getStorageSync('token');
  if (!token) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    uni.navigateTo({
      url: "/pages/login/index"
    });
    return;
  }
  uni.request({
    url: `${Config.API_HOST}/carts/?token=${token}`,
    method: 'GET',
    success: (res) => {
      const carts = res.data;
      const existingItem = carts.find(cartItem => cartItem.id === item.id);

      if (existingItem) {
        const newQuantity = existingItem.quantity + 1;
        uni.request({
          url: `${Config.API_HOST}/carts/${existingItem.id}`,
          method: 'PUT',
          data: {
           ...existingItem,
            quantity: newQuantity
          },
          success: (updateRes) => {
            uni.showToast({
              title: '加入购物车成功',
              icon:'success',
              duration: 2000
            });
            fetchCartData();
          },
          fail: (updateErr) => {
            console.error('购物车商品数量更新失败', updateErr);
          }
        });
      } else {
        const cartItem = {
         ...item,
          quantity: 1,
          shopname: shop.value[0].name,
          token: uni.getStorageSync('token')
        };
        uni.request({
          url: `${Config.API_HOST}/carts?token=${token}`,
          method: 'POST',
          data: cartItem,
          success: (addRes) => {
            uni.showToast({
              title: '加入购物车成功',
              icon:'success',
              duration: 2000
            });
            fetchCartData();
          },
          fail: (addErr) => {
            console.error('商品添加到购物车失败', addErr);
          }
        });
      }
    },
    fail: (err) => {
      console.error('获取购物车数据失败', err);
    }
  });
};

// 显示购物车浮层
const shows = () => {
  const token = uni.getStorageSync('token');
  if (!token) {
    uni.showToast({
      title: '请先登录',
      icon: 'none',
      duration: 2000
    });
    return;
  }
  showCartPopup.value =!showCartPopup.value;
  fetchCartData();
   
};

// 确认清空购物车
const confirmClearCart = () => {
  const token = uni.getStorageSync('token');
  if (!token) {
    uni.showToast({
      title: '请先登录',
      icon: 'none',
      duration: 2000
    });
    return;
  }

  uni.showModal({
    title: '提示',
    content: '你确定要清空购物车吗？',
    confirmText: '确定',
    cancelText: '取消',
    success: (res) => {
      if (res.confirm) {
        clearCart();
      }
    }
  });
};

// 清空购物车
const clearCart = () => {
  const deletePromises = cartItems.value.map((product) => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: `${Config.API_HOST}/carts/${product.id}`,
        method: "DELETE",
        success: (res) => {
          resolve(res);
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  });
  Promise.all(deletePromises)
   .then(() => {
      fetchCartData();
    })
   .catch((error) => {
      console.error('清空购物车失败:', error);
    });
  showCartPopup.value = false;
};

// 获取购物车数据
const fetchCartData = () => {
  const token = uni.getStorageSync('token');
  if (!token) {
    uni.request({
      url: `${Config.API_HOST}/hotList`,
      method: 'GET',
      success: (res) => {
        const updatePromises = res.data.map(item => {
          return uni.request({
            url: `${Config.API_HOST}/hotList/${item.id}`,
            method: 'PATCH',
            data: {
              checked: false
            }
          });
        });
        Promise.all(updatePromises)
          .then(() => {
            console.log('所有checked字段已更新为false');
          })
          .catch((error) => {
            console.error('更新checked字段失败:', error);
          });
      }
    });
    return;

  } else {
    uni.request({
      url: `${Config.API_HOST}/carts?shopname=${shop.value[0].name}&token=${token}`,
      method: "GET",
      success: (res) => {
        cartItems.value = res.data;
        // 计算购物车商品数量并赋值给num
        num.value = cartItems.value.reduce((acc, item) => acc + item.quantity, 0); 
      }
    });
    uni.request({
         url: `${Config.API_HOST}/attention?name=${shop.value[0].name}&token=${token}`,
         method: "GET",
         success: (res) => {
           if (Array.isArray(res.data) && res.data.length > 0) {
             isFollowed.value = res.data[0].checked;
           } else {
             isFollowed.value = false; // 设置默认值
           }
         },
         fail: (err) => {
           console.error('获取关注状态失败:', err);
           isFollowed.value = false; // 请求失败时也设置默认值
         }
       });
  }
};

// 页面显示时获取购物车数据
onShow(() => {
  fetchCartData();
});

const select = (id) => {
  const token = uni.getStorageSync('token');  
  if (!token) {
    uni.showToast({
      title: '请先登录',
      icon: 'none',
      duration: 2000
    });	
    return;
  }	
  // 先检查是否已存在
  uni.request({
    url: `${Config.API_HOST}/attention?_id=${id}&token=${token}`,
    method: 'GET',
    success: (res) => {
      if (res.data && res.data.length > 0) {
        // 如果存在，只更新checked
        uni.request({
          url: `${Config.API_HOST}/attention/${res.data[0].id}`,
          method: 'PATCH',
          data: {
            checked:!isFollowed.value
          },
          success: () => {
            isFollowed.value =!isFollowed.value;
          }
        });
      } else {
        // 如果不存在，添加新数据
        const {_id, name, imgUrl, sales, expressLimit, expressPrice, slogan, kilometer} = shop.value[0];
        uni.request({
          url: `${Config.API_HOST}/attention`,
          method: 'POST',
          data: {
            _id,
            name,
            imgUrl,
            sales,
            expressLimit,
            expressPrice,
            slogan,
            kilometer,
            token: token,
            checked:!isFollowed.value
          },
          success: () => {
            isFollowed.value =!isFollowed.value;
          }
        });
      }
    }
  });
}

// 去结算方法
const goToCheckout = (shopname) => {
  uni.navigateTo({
    url: "/pages/checkout/index?shopname=" + shopname,
  });
};
</script>

<style scoped>
/* 购物车浮层样式 */
.num{
	display: block;
	width: 15px;
	height: 15px;
	color: white;
	line-height: 15px;
	text-align: center;
	border:1px solid red;
	background-color: #e93b3b;
	border-radius: 100%;
	position: relative;
	left: -16px;
	top: -7px;
}
.cart-popup {
  position: fixed;
  bottom: 70px;
  left: 0;
  right: 0;
  background: white;
  box-shadow: 0 -8rpx 16rpx rgba(0, 0, 0, 0.08);
  padding: 15rpx;
  z-index: 999;
}

/* 操作按钮区域样式 */
.cart-ops {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.select-all,
.clear-cart {
  font-size: 30rpx;
  color: #333;
}

/* 购物车商品列表样式 */
.cart-items {
  max-height: 200rpx;
  overflow-y: auto;
  margin-bottom: 15rpx;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 10rpx;
  border-bottom: 1rpx solid #eaeaea;
}

.cart-item-img {
  width: 80rpx;
  height: 80rpx;
  border-radius: 10rpx;
  margin-right: 15rpx;
}

.cart-item-info {
  flex: 1;
}

.cart-item-title {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 5rpx;
}

.cart-item-sales {
  font-size: 24rpx;
  color: #999;
}

.cart-item-price {
  font-size: 28rpx;
  color: #e93b3b;
}

.cart-item-count {
  display: flex;
  align-items: center;
}

.count-value {
  font-size: 24rpx;
  color: #333;
  margin: 0 10rpx;
}

.footer-content {
	position: fixed;
	bottom: 0px;
  height: 70px;
  width: 92vw;
  display: flex;
  justify-content: space-around;
  align-items: center;
  background-color: white;
  box-shadow: 0 -4rpx 8rpx rgba(0, 0, 0, 0.06);
padding: 0 20rpx;
}

.cart-total {
  display: flex;
  align-items: center;
}

.shopimg {
  width: 60rpx;
  height: 60rpx;
  margin-right: 10rpx;
}

.total-price {
  font-size: 40rpx;
  color: #333;
}

.checkout-button {
  padding: 10rpx 20rpx;
  background-color: #007AFF;
  color: white;
  border: none;
  border-radius: 8rpx;
  font-size: 30rpx;
  transition: background-color 0.3s;
  margin-right: 0px;
}

.checkout-button:hover {
  background-color: #005EA6;
}

/* 整体布局 */
.content {
  background: #f8f8f8;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 商家头部 */
.shop-header {
  padding: 30rpx;
  background: white;
  display: flex;
  align-items: center;
  box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.08);
}

.shop-logo {
  width: 160rpx;
  height: 160rpx;
  border-radius: 10rpx;
  margin-right: 30rpx;
}

.shop-info {
  flex: 1;
}

.shop-name {
  font-size: 38rpx;
  font-weight: 700;
  color: #222;
  margin-bottom: 15rpx;
  display: block;
}

.stats-container {
  flex-wrap: wrap;
  margin-bottom: 12rpx;
}

.stat-item {
  font-size: 26rpx;
  color: #777;
  margin-right: 25rpx;
}

.slogan {
  color: #e93b3b;
  font-size: 28rpx;
}

/* 主体布局 */
.main-container {
  display: flex;
  flex: 1;
}

/* 左侧导航 */
.nav-sidebar {
  width: 220rpx;
  background: #f0f0f0;
}

.nav-item {
  height: 120rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30rpx;
  color: #888;
  position: relative;
  transition: all 0.3s;
}

.nav-item.active {
  background: white;
  color: #e93b3b;
  font-weight: 600;
  box-shadow: 4rpx 0 8rpx rgba(0, 0, 0, 0.05);
}

.nav-item.active::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 8rpx;
  height: 50rpx;
  background: #e93b3b;
  border-radius: 5rpx;
}

/* 右侧商品 */
.product-list {
  flex: 1;
  padding: 0 30rpx;
  background: white;
}

.product-card {
  background: white;
  border-radius: 15rpx;
  margin-bottom: 25rpx;
  padding: 25rpx;
  display: flex;
  box-shadow: 0 6rpx 14rpx rgba(0, 0, 0, 0.06);
}
.product-card:last-child{
	margin-bottom: 120px;
}
.product-img {
  width: 180rpx;
  height: 180rpx;
  border-radius: 10rpx;
  margin-right: 30rpx;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-title {
  font-size: 32rpx;
  color: #333;
  line-height: 1.5;
  display: block;
  margin-bottom: 12rpx;
}

.sales {
  font-size: 26rpx;
  color: #999;
  display: block;
  margin-bottom: 18rpx;
}

.price-container {
  display: flex;
  align-items: baseline;
}

.current-price {
  color: #e93b3b;
  font-size: 36rpx;
  font-weight: 700;
  margin-right: 18rpx;
}

.old-price {
  color: #999;
  font-size: 28rpx;
  text-decoration: line-through;
}

.add {
  align-self: flex-start;
  margin-top: 3rpx;
  background-color: #e93b3b;
  color: white;
  border: none;
  border-radius: 8rpx;
  font-size: 20rpx;
  transition: background-color 0.3s;
}
</style>